package com.ticket.sass.admin.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.mapper.TenantWxaConfigMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.provider.TenantWxaConfigEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-05-14
 */
@Service
public class TenantWxaConfigServiceImpl extends ServiceImpl<TenantWxaConfigMapper, TenantWxaConfigEntity> implements BaseService<TenantWxaConfigEntity> {
    public Map<Long, TenantWxaConfigEntity> getConfigsByTenantIds(List<Long> tenantIds) {
        if (tenantIds.size() == 0){
            return new HashMap<>();
        }
        
        // 创建查询条件，筛选 tenantId 在列表中的记录
        QueryWrapper<TenantWxaConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("tenant_id", tenantIds);
        
        // 查询符合条件的所有记录
        List<TenantWxaConfigEntity> tenantWxaConfigEntities = list(queryWrapper);
        
        // 将查询结果转换为 Map<tenantId, TenantWxaConfigEntity>
        return tenantWxaConfigEntities.stream()
            .collect(Collectors.toMap(TenantWxaConfigEntity::getTenantId, config -> config));
    }
    
    public TenantWxaConfigEntity getConfigsByTenantId(Long tenantId) {

        
        // 创建查询条件，筛选 tenantId 在列表中的记录
        QueryWrapper<TenantWxaConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", tenantId);
      
        return this.getOne(queryWrapper);
    }
    
    
    public void saveOrUpdateWxaConfig(String appid, String secret, Long tenantId) {
        // 查询是否存在记录
        QueryWrapper<TenantWxaConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", tenantId);
        TenantWxaConfigEntity themeConfigEntity = getOne(queryWrapper);
        
        if (themeConfigEntity != null) {
            // 存在记录，更新 data 字段
            UpdateWrapper<TenantWxaConfigEntity> updateWrapper = new UpdateWrapper<>();
            queryWrapper.eq("tenant_id", tenantId);
            updateWrapper.set("appid", appid);
            updateWrapper.set("secret", secret);
            update(updateWrapper);
        } else {
            // 不存在记录，新增一条
            TenantWxaConfigEntity newThemeConfigEntity = new TenantWxaConfigEntity();
            newThemeConfigEntity.setTenantId(tenantId);
            newThemeConfigEntity.setAppid(appid);
            newThemeConfigEntity.setSecret(secret);
            newThemeConfigEntity.setTenantId(tenantId);
            save(newThemeConfigEntity);
        }
    }
}